from django.conf import settings

from ceph.models import CephCluster
from django.core.checks import Warning
from django.core.exceptions import ValidationError


def ceph_settings_update():
    ceph_cluster = {}
    errors = []

    s3_multipart_pool_name = getattr(settings, 'MULTIPART_POOL_CONF', None)
    if not s3_multipart_pool_name:
        raise ValidationError('请指定S3多部分上传MULTIPART_POOL_CONF的配置。')

    try:
        ceph_cluster_list = CephCluster.objects.all()
        if not ceph_cluster_list:
            errors.append(Warning('未配置CEPH集群信息，服务启动后需要先登录后端配置ceph集群信息。'))
            return errors
    except Exception as e:
        return errors

    for ceph_cluster_info in ceph_cluster_list:

        if not s3_multipart_pool_name[ceph_cluster_info.alias].get('MULTIPART_POOL_NAME'):
            raise ValidationError(f'请查看S3多部分上传MULTIPART_POOL_CONF的配置是否正确。'
                                  f'未获取到别名{ceph_cluster_info.alias}中MULTIPART_POOL_NAME的值')

        # 默认是最新的配置文件
        ceph_pool_conf = {
            'CLUSTER_NAME': ceph_cluster_info.cluster_name,
            'USER_NAME': ceph_cluster_info.user_name,
            'DISABLE_CHOICE': ceph_cluster_info.disable_choice,
            'CONF_FILE_PATH': ceph_cluster_info.config_file,
            'KEYRING_FILE_PATH': ceph_cluster_info.keyring_file,
            'POOL_NAME': tuple(ceph_cluster_info.pool_names),
            'MULTIPART_POOL_NAME': s3_multipart_pool_name[ceph_cluster_info.alias].get('MULTIPART_POOL_NAME'),
        }
        ceph_cluster[ceph_cluster_info.alias] = ceph_pool_conf

    settings.CEPH_RADOS = ceph_cluster
    return errors
